package com.example.storage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import mealhistory.Mealitem;

public class Mealdatabase extends SQLiteOpenHelper {

    public static final String CREATE_MEAL = "create table meal ("
            +"id integer primary key autoincrement,"
            +"date,"
            +"type,"
            +"food not null,"
            +"weight not null,"
            +"consumption not null)";


    public Cursor getbreakfastData() {
        SQLiteDatabase db=this.getWritableDatabase();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = sdf.format(new Date());
        String query = "SELECT * FROM meal WHERE type = '早餐' AND date = '" + currentDate + "'";

        Cursor cursor = db.rawQuery(query, null);
        return cursor;
    }

    public Cursor getlunchData() {
        SQLiteDatabase db=this.getWritableDatabase();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = sdf.format(new Date());
        String query = "SELECT * FROM meal WHERE type = '午餐' AND date = '" + currentDate + "'";

        Cursor cursor = db.rawQuery(query, null);
        return cursor;
    }

    public Cursor getdinnerData() {
        SQLiteDatabase db=this.getWritableDatabase();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = sdf.format(new Date());
        String query = "SELECT * FROM meal WHERE type = '晚餐' AND date = '" + currentDate + "'";

        Cursor cursor = db.rawQuery(query, null);
        return cursor;
    }

    public Cursor getDistinctDateType() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT DISTINCT date, type FROM meal ORDER BY date DESC";
        return db.rawQuery(query, null);
    }

    public Cursor getMealDataByDateAndType(String date, String type) {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] columns = new String[]{"id", "food", "weight", "consumption"};
        String selection = "date=? AND type=?";
        String[] selectionArgs = new String[]{date, type};
        return db.query("meal", columns, selection, selectionArgs, null, null, null);
    }

    public Map<String, Float> getCaloriesLastSevenDays() {
        SQLiteDatabase db = this.getReadableDatabase();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Map<String, Float> weekCalories = new LinkedHashMap<>();  // 使用 LinkedHashMap 以保持插入顺序

        for (int i = 0; i < 7; i++) {
            String date = sdf.format(calendar.getTime());
            Cursor cursor = db.rawQuery("SELECT SUM(consumption) FROM meal WHERE date = ?", new String[]{date});
            if (cursor.moveToFirst()) {
                float total = cursor.getFloat(0);  // 获取总热量
                weekCalories.put(date, total);  // 将日期和总热量存储到 Map 中
            } else {
                weekCalories.put(date, 0f);  // 如果没有数据，使用 0f 作为默认值
            }
            cursor.close();
            calendar.add(Calendar.DATE, -1);
        }
        db.close();
        return weekCalories;
    }

    private Context mContext;

    public Mealdatabase(Context context,String name,SQLiteDatabase.CursorFactory factory,int version){
        super(context,name,factory,version);
        mContext=context;
    }

    public void deleteMealItem(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        int affectedRows = db.delete("meal", "id = ?", new String[]{String.valueOf(id)});
        db.close();
        Log.d("DB_DELETE", "Affected rows: " + affectedRows); // 添加日志打印，查看是否真的执行了删除操作
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_MEAL);
        Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists meal");
        onCreate(db);
    }
}
